import React, { useState, useEffect, useMemo } from 'react';
import { Skeleton, Tag } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import loadable from '@loadable/component';

import useAuthAction from '@/hooks/useAuthAction';
import { setStore } from '@/reducers/common';
import { formatNumber } from '@/utils';
import { MERCH_DETAIL, ACCOUNT } from '@/config/url';
import { COLORS } from '@/config';
import { likeMerch, unLikeMerch, haveMerchUp, haveMerchDown, wantMerchUp, wantMerchDown } from '@/service/api';
import styles from './index.module.scss';

const LikeHwButton = loadable(() => import('@/pages/MerchDetail/components/LikeHwButton'), {fallback: <Skeleton.Button active/>});
const IconFont = loadable(() => import('@/components/IconFont'));

// MerchItem：参考 Home 下的卡片样式与结构，交互在组件内实现
const MerchItem = props => {
  const initState = () => ({
    isLike: 2, // 1-已点击 2-未点击
    likeCount: 0,
    isHaveIt: 2, // 1-已点击 2-未点击
    haveItCount: 0,
    isWantIt: 2, // 1-已点击 2-未点击
    wantItCount: 0,
  });
  const [state, setState] = useState(initState);
  const { item, type='merch', className } = props;
  const navigate = useNavigate();
  const { userInfo={} } = useSelector(s => s.common);
  const dispatch = useDispatch();
  const withAuth = useAuthAction();
  const showFooter = ['merch', 'tabmerch'].includes(type);

  // 跳转详情页
  const toDetail = () => {
    navigate(`${MERCH_DETAIL}?id=${item.goodsId}`);
  };

  // 跳用户中心
  const toAccount = e => {
    e?.preventDefault?.();
    e?.stopPropagation?.();
    navigate(`${ACCOUNT}?uid=${item.lastEditorId}`);
  };

  // 点赞/取消点赞核心逻辑
  const handleFanCore = async (e) => {
    e?.preventDefault?.();
    e?.stopPropagation?.();

    // 1-已点击 2-未点击
    const { isLike, likeCount } = state;
    const hasClick = 1 === isLike;
    const api = hasClick ? unLikeMerch : likeMerch;
    const [res, err] = await api({ id: item.goodsId });
    if (err) return;
    setState(o => ({ 
      ...o, 
      isLike: 1 === o.isLike ? 2 : 1, 
      likeCount: 1 === o.isLike ? o.likeCount - 1 : o.likeCount + 1 
    }));
  };
  
  // 点赞/取消点赞（带登录检查）
  const handleFan = (e) => {
    e?.preventDefault?.();
    e?.stopPropagation?.();
    withAuth(handleFanCore)(e);
  };

  // 同步外部数据到本地状态（首次渲染或 item 变化时）
  useEffect(() => {
    setState(o => ({
      ...o,
      isLike: item?.isLike || 2,
      likeCount: Number(item?.likeCount) || 0,
      isHaveIt: item?.isHaveIt || 2,
      haveItCount: Number(item?.haveItCount) || 0,
      isWantIt: item?.isWantIt || 2,
      wantItCount: Number(item?.wantItCount) || 0,
    }));
  }, [item?.goodsId]);

  return (
    <div className={`${styles['root']} ${className}`}>
      <div className={styles['card']} onClick={toDetail}>
        <div className={styles['card-header']}>
          <div className={styles['avatar']} onClick={toAccount}><img src={item.lastEditorAvatar ? `${item.lastEditorAvatar}?x-oss-process=image/resize,p_20` : '/images/default-avatar.png'} alt={item.lastEditorName} /></div>
          <div className={styles['publisher']} onClick={toAccount}>{item.lastEditorName || item.lastEditorId || '--'}</div>
          <div className={styles['header-actions']}>
            <div className={styles['fav-group']}>
              <div
                className={`${styles['fav-chip']} ${1 === state.isLike ? styles['active'] : ''}`}
                role="button"
                tabIndex={0}
                onClick={handleFan}
              >
                <IconFont name={1===state.isLike ? 'icon-aixin-2' : 2===state.merchInfo?.isHaveIt ? 'icon-like-1' : 'icon-like-1'}/>
                <span>{formatNumber(state.likeCount, 0)}</span>
              </div>
            </div>
          </div>
        </div>

        <div className={styles['thumb']}>
          { !!item.categoryName && <div className={styles['category']}>{item.categoryName || ''}</div> }
          <img src={item?.mainGoodsImages} alt={item.goodsName} />
        </div>

        <div className={styles['meta']}>
          <div className={styles['meta-title']} title={item.goodsName}>{item.goodsName}</div>
          <div className={styles['meta-details']}>
            <div className={styles['meta-row']} title={item.seriesName}>
              <span className={styles['meta-label']}>作品</span>
              <span className={styles['meta-value']}>{item.seriesName}</span>
            </div>
            <div className={styles['meta-row']} title={item.charactarName}>
              <span className={styles['meta-label']}>角色</span>
              <span className={styles['meta-value']}>{item.charactarName}</span>
            </div>
          </div>
        </div>

        {
          showFooter && <div className={styles['footer']}>
            <LikeHwButton showLike={false} dataSource={item} type={type}/>
          </div>
        }
      </div>
    </div>
  );
};

export default MerchItem;